package com.jby.autotest.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jby.autotest.model.User;
import com.jby.autotest.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/selectUserByPage")
    @ResponseBody
    public Map<String,Object> selectByPage(User user,
                                           @RequestParam(required = false, defaultValue = "1") int page,
                                           @RequestParam(required = false, defaultValue = "10") int rows){

        try {
            PageHelper.startPage(page, rows);
            Map<String,Object> map = new HashMap<>();
            List<User> userList = userService.selectByPage(user);
            PageInfo<User> pageInfo = new PageInfo<>(userList);
            map.put("total", pageInfo.getTotal());
            map.put("rows",userList);
            return map;
        }catch (Exception e){
            e.printStackTrace();
        }
       return null;
    }

    @RequestMapping(value = "/saveUser", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> saveUser(User user){
        Map<String,Object> map = new HashMap<>();

        try{
            userService.insertSelective(user);
            map.put("status","success");
        }catch (Exception e){
            map.put("status","fail");
            return map;
        }
        return map;
    }

    @RequestMapping(value = "/updateUser")
    @ResponseBody
    public Map<String,Object> updateUser(User user){

        Map<String,Object> map = new HashMap<>();

        try {
            userService.updateByPrimaryKeySelective(user);
            map.put("status","success");
        }catch (Exception e){
            map.put("status","fail");
            return map;
        }
        return map;
    }


    @RequestMapping(value = "/deleteUser")
    @ResponseBody
    public Map<String,Object> deleteUser(@RequestParam(value = "ids") String ids){
        Map<String,Object> map = new HashMap<>();

        String[] idArray = ids.split(",");
        try {
            for (String s:idArray
                 ) {
                userService.deleteByPrimaryKey(Integer.parseInt(s));
            }
        }catch(Exception e){
            e.printStackTrace();
            map.put("status","fail");
            return map;
        }

        map.put("status","success");
        return map;
    }
}

















